// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

async function getUser(openid) {
  const { OPENID } = cloud.getWXContext()
  const db = cloud.database()

  return db.collection('user').where({
    openid: openid || OPENID
  }).get()
}

async function list({openid, page, size, ...rest}) {
  const skip = (page - 1) * size
  const db = cloud.database()
  const _ = db.command
  if (Array.isArray(openid)) {
    rest.openid = _.in(openid)
  }

  return db.collection('user').where({
    ...rest
  }).field({
    nickName: true,
    openid: true,
    avatarUrl: true,
  })
  .skip(skip)
  .limit(size)
  .get()
}

async function insertUser(user) {
  const { OPENID } = cloud.getWXContext()
  const db = cloud.database()

  return db.collection('user').add({
    data:{
      ...user,
      openid: user.openid || OPENID,
      labels: [],
      follow: [],
      desc: '',
      createdTime: db.serverDate(),
      updatedTime: db.serverDate(),
      lastLoginTime: db.serverDate(),
      isValid: 1, // 逻辑删除
      status: 0, // 
    }
  })
}
async function updateUser(user) {
  const db = cloud.database()
  const {_id, ...rest} = user
  return db.collection('user').doc(_id).update({
    data:{
      ...rest,
      updatedTime: db.serverDate(),
    }
  })
}

async function follow(user) {
  const db = cloud.database()
  const _ = db.command
  const {_id, followId} = user
  return db.collection('user').doc(_id).update({
    data: {
      follow: _.addToSet(followId)
    }
  })
}

async function unfollow(user) {
  const db = cloud.database()
  const _ = db.command
  const {_id, followId} = user
  return db.collection('user').doc(_id).update({
    data:{
      follow: _.pull(followId)
    }
  })
}

// 云函数入口函数
exports.main = async ({action, data}) => {

  const func = {
    get: getUser,
    insert: insertUser,
    update: updateUser,
    list,
    follow,
    unfollow
  }[action]
  if (func) return func(data)
}
